package org.example.curriculum_design_6_16.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.curriculum_design_6_16.entity.pojo.IntellectualProperty;
import org.example.curriculum_design_6_16.entity.pojo.IpScoringRule;
import org.example.curriculum_design_6_16.entity.vo.IntellectualPropertyVo;
import org.example.curriculum_design_6_16.mapper.IpScoringRuleMapper;
import org.example.curriculum_design_6_16.service.IntellectualPropertyService;
import org.example.curriculum_design_6_16.mapper.IntellectualPropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 郑凯
 * @description 针对表【intellectual_property(知识产权记录表)】的数据库操作Service实现
 * @createDate 2025-06-23 09:02:06
 */
@Service
public class IntellectualPropertyServiceImpl extends ServiceImpl<IntellectualPropertyMapper, IntellectualProperty>
        implements IntellectualPropertyService{
    @Autowired
    private IntellectualPropertyMapper intellectualPropertyMapper;

    @Autowired
    private IpScoringRuleMapper ipScoringRuleMapper;

    @Override
    public int addIntellectualProperty(IntellectualProperty intellectualProperty) {
        // 设置默认状态为已通过
        if (intellectualProperty.getReviewStatus() == null) {
            intellectualProperty.setReviewStatus("APPROVED");
        }
        if (intellectualProperty.getReviewComment() == null) {
            intellectualProperty.setReviewComment("自动通过");
        }
        calculateScore(intellectualProperty);
        return intellectualPropertyMapper.insertIntellectualProperty(intellectualProperty);
    }

    @Override
    public int updateIntellectualProperty(IntellectualProperty intellectualProperty) {
        // 设置默认状态为已通过
        if (intellectualProperty.getReviewStatus() == null) {
            intellectualProperty.setReviewStatus("APPROVED");
        }
        if (intellectualProperty.getReviewComment() == null) {
            intellectualProperty.setReviewComment("自动通过");
        }
        calculateScore(intellectualProperty);
        return intellectualPropertyMapper.updateIntellectualProperty(intellectualProperty);
    }

    @Override
    public int deleteIntellectualProperty(Integer id) {
        return intellectualPropertyMapper.deleteIntellectualPropertyById(id);
    }

    @Override
    public IntellectualPropertyVo getIntellectualPropertyById(Integer id) {
        IntellectualProperty ip = intellectualPropertyMapper.getIntellectualPropertyById(id);
        if (ip == null) throw new RuntimeException("未找到ID为" + id + "的知识产权记录");
        return convertToVo(ip);
    }

    @Override
    public List<IntellectualPropertyVo> getIntellectualPropertiesByStudentId(String studentId) {
        List<IntellectualProperty> ips = intellectualPropertyMapper.getIntellectualPropertiesByStudentId(studentId);
        List<IntellectualPropertyVo> ipVos = new ArrayList<>();
        
        for (IntellectualProperty ip : ips) {
            ipVos.add(convertToVo(ip));
        }
        
        return ipVos;
    }

    @Override
    public List<IntellectualPropertyVo> getAllIntellectualProperties() {
        List<IntellectualProperty> ips = intellectualPropertyMapper.getAllIntellectualProperties();
        List<IntellectualPropertyVo> ipVos = new ArrayList<>();
        
        for (IntellectualProperty ip : ips) {
            ipVos.add(convertToVo(ip));
        }
        
        return ipVos;
    }

    @Override
    public Double getTotalScore(String studentId) {
        List<IntellectualProperty> list = intellectualPropertyMapper.getIntellectualPropertiesByStudentId(studentId);
        Double totalScore = 0.0;
        for (IntellectualProperty intellectualProperty : list) {
            Double score = intellectualProperty.getScore();
            if (score != null) {
                totalScore += score;
            }
        }

        return totalScore;
    }

    @Override
    public Double getTotalScore(String studentId, String academicYear) {
        List<IntellectualProperty> list = intellectualPropertyMapper.getIntellectualPropertiesByStudentIdAndYear(studentId, academicYear);
        Double totalScore = 0.0;
        for (IntellectualProperty intellectualProperty : list) {
            // 只计算已审核通过的知识产权
            if (!"APPROVED".equals(intellectualProperty.getReviewStatus())) {
                continue;
            }
            Double score = intellectualProperty.getScore();
            if (score != null) {
                totalScore += score;
            }
        }

        return totalScore;
    }

    @Override
    public List<String> getAllDistinctIpTypes() {
        return ipScoringRuleMapper.getAllDistinctIpTypes();
    }

    /**
     * 将IntellectualProperty转换为IntellectualPropertyVo
     * @param ip 知识产权记录
     * @return 知识产权记录VO
     */
    private IntellectualPropertyVo convertToVo(IntellectualProperty ip) {
        IntellectualPropertyVo vo = new IntellectualPropertyVo();
        vo.setId(ip.getId());
        vo.setStudentId(ip.getStudentId());
        vo.setIpType((String) ip.getIpType());
        vo.setName(ip.getName());
        vo.setApplicationNumber(ip.getApplicationNumber());
        vo.setApplicationDate(ip.getApplicationDate());
        vo.setIpStatus((String) ip.getIpStatus());
        vo.setAuthorizationNumber(ip.getAuthorizationNumber());
        vo.setAuthorizationDate(ip.getAuthorizationDate());
        vo.setCertificateNumber(ip.getCertificateNumber());
        vo.setIsTeamLeader(ip.getIsTeamLeader());
        vo.setTeamSize(ip.getTeamSize());
        vo.setScore(ip.getScore());
        vo.setProofUrl(ip.getProofUrl());
        vo.setReviewStatus((String) ip.getReviewStatus());
        vo.setReviewComment(ip.getReviewComment());
        vo.setAcademicYear(ip.getAcademicYear());
        vo.setCreatedAt(ip.getCreatedAt());
        vo.setUpdatedAt(ip.getUpdatedAt());
        
        // 查询知识产权评分规则获取类型和状态描述
        if (ip.getIpType() != null && ip.getIpStatus() != null) {
            IpScoringRule rule = ipScoringRuleMapper.getIpScoringRuleByTypeAndStatus(
                    (String) ip.getIpType(),
                    (String) ip.getIpStatus()
            );
            if (rule != null) {
                vo.setIpTypeDescription(rule.getDescription());
                vo.setIpStatusDescription(rule.getDescription());
            }
        }
        
        return vo;
    }

    private void calculateScore(IntellectualProperty intellectualProperty) {
        // 根据规则计算得分
        IpScoringRule rule = ipScoringRuleMapper.getIpScoringRuleByTypeAndStatus(
                (String) intellectualProperty.getIpType(),
                (String) intellectualProperty.getIpStatus()
        );

        if (rule != null) {
            // 直接使用基础分数，不计算团队加分
            Double score = rule.getScore();
            intellectualProperty.setScore(score);
        } else {
            // 如果找不到评分规则，设置默认分数为0
            intellectualProperty.setScore(0.0);
        }
    }
}